function t(t, i, e) {
    return i in t ? Object.defineProperty(t, i, {
        value: e,
        enumerable: !0,
        configurable: !0,
        writable: !0
    }) : t[i] = e, t;
}

var i, e = getApp();
var app = getApp();
// 在页面中定义插屏广告
let interstitialAd = null

Page((i = {
    data: {
        auth: false,
        invite: '',
        uuid: '',
        balance: 0,
        num: 0,
        quesTotal: 0,
        total: 0,
        userInfo: {
            nickName: "未登录",
            avatarUrl: "../../resource/icon/default.png",
            gold_num: 0,
            balance: 0,
            level: 0
        },
        windowH: 0,
        boxH: 0,
        rankListH: 0,
        showRank: !1,
        rank: {
            type: "level",
            page: 1,
            page_size: 10,
            list: [],
            more: !0
        },
        registerStatus: !1,
        icons: {
            jinbi: "/resource/icon/index/jinbi.png",
            balance: "/resource/icon/index/redbag.png",
            close_515151: "/resource/icon/index/close_515151.png",
            rank: "/resource/icon/index/rank.png",
            invite: "/resource/icon/index/invite.png",
            award: "/resource/icon/index/award.png",
            broad: "/resource/icon/gg.png",
            service: "/resource/icon/index/service.png",
            recommend: "/resource/icon/index/recommend.png",
            feedback: "/resource/icon/index/feedback.png",
            video: "/resource/icon/index/video.png"
        },
        images: {
            title: "/resource/images/title2.png"
        },
        setting: {
            unit_id: ""
        },
        shareScene: "home",
        ylStatus: "hide",
        adv: {
            status: !1,
            data: []
        },
        loginCompStatus: !1,
        animate: "dsne",
        broadList: [],
        showBroad: true,
        ylboxh: "",
        gzh_box_status: !1,
        canIUseInterstitialAd: e.canIUseInterstitialAd,
        interstitialAd: null
    },
    onReady: function() {
        this.initSystemInfo(), e.initConfig(this.initConfigBack);
    },
    initSystemInfo: function() {
        var t = wx.getSystemInfoSync(), i = t.windowHeight * (750 / t.screenWidth), e = i - 100, n = e - 224;
        this.setData({
            windowH: i,
            boxH: e,
            rankListH: n
        });
    },
    initConfigBack: function() {
        var t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : null, i = this;
        if (null != t) {
            var e = t.setting, n = t.adv, a = "360rpx";
            e.status && (e.data.hasOwnProperty("gzh_img") && "" != e.data.gzh_img && "" != e.data.gzh_ewm_img && (a = "480rpx"), 
            i.setData({
                setting: e.data
            }), "" !== e.data.name && wx.setNavigationBarTitle({
                title: e.data.name
            })), i.setData({
                adv: n,
                ylboxh: a
            }), i.initInterstitialAd();
        }
    },
    onShareTimeline: function(res){
        if(res.from === 'menu'){
          console.log(res.target);
        }
        return {
          title: '朋友邀请你来参加成语答题了，快来露两手吧',
          path: 'pages/index/index'
        }
    },
    onShow: function() {
        console.log("index onShow");
        this.onGetOpenid();
        // 在适合的场景显示插屏广告
        if (interstitialAd) {
            interstitialAd.show().catch((err) => {
            console.error(err)
            })
        }
    },
    onLoad: function(options) {

        // 在页面onLoad回调事件中创建插屏广告实例
        if (wx.createInterstitialAd) {
            interstitialAd = wx.createInterstitialAd({
            adUnitId: 'adunit-d5cb621175223b28'
            })
            interstitialAd.onLoad(() => {})
            interstitialAd.onError((err) => {})
            interstitialAd.onClose(() => {})
        }
        
 
  
        if(options.uuid){
            
            this.setData({
                uuid: options.uuid,
                invite: options.openid
            },()=>{
                this.addInvite();
            })
        }
        console.log("index Onload");
        this.onQuery();
    },
    addInvite: function(){
        const db = wx.cloud.database();
        db.collection('invites').add({
          // data 字段表示需新增的 JSON 数据
          data: {
                invite: this.data.invite,
                uuid: this.data.uuid,
                userInfo: app.globalData.userInfo,
                status: this.data.auth ? 1 : 0,
                time: new Date()
          }
        })
        .then(res => {
          console.log(res)
          console.log('[数据库] [查询记录] 成功: ', res);
          this.update();
      
        })
        .catch((err)=>{
          console.log(err)
        
        })
    },
    update: function(){
        let that = this;

        const db = wx.cloud.database()

        let _id = this.data.invite;
        const _ = db.command
        db.collection('profiles').doc(_id).update({
            data: {
                // 表示指示数据库将字段自增 -100
                num: _.inc(100)
            }
        })
        .then(res=>{
            console.log(res)
        })
        .catch(err=>{
            console.log(err);
        })
    },
    onQuery: function(){

        const db = wx.cloud.database()
        db.collection('records')
        .get().then(res => {
            console.log('[数据库] [查询记录] 成功: ', res)
            wx.hideLoading()
            let arr = res.data;
            let records = [];
            arr.forEach((element,index) => {
                element.index = index;
                records.push(element);
            });
            this.setData({
                records
            });
        })
        
    },
    getRankList: function(){
        let that = this;
        // 调用云函数
        wx.cloud.callFunction({
          name: 'getRanks',
          data: {}
        })
        .then(res=>{
          console.log('[云函数] [getRanks]: ', res)
          let items = res.result.data;
          let historys = [];
          items.forEach((element,index) => {
              element.index = index;
              historys.push(element);
          });
          this.setData({
            historys
          });

         
        })
        .catch(err=>{
          console.error('[云函数] [getRanks] 调用失败', err)
          wx.navigateTo({
            url: '../deployFunctions/deployFunctions',
          })
        })
        return;
        const db = wx.cloud.database()
        db.collection('historys')
        .get().then(res => {
          console.log('[数据库] [查询记录] 成功: ', res)
          wx.hideLoading()
          let arr = res.data;
          let historys = [];
          arr.forEach((element,index) => {
              element.index = index;
              historys.push(element);
          });
          this.setData({
            historys
          });
        })
    },
    authGo: function(){
        if(app.globalData.auth){
            wx.showModal({
                showCancel: false,
                title: '提示',
                confirmText: '我知道了',
                content: '您已完成授权',
                success (res) {
                    if (res.confirm) {
                    console.log('用户点击确定')
        
                    } else if (res.cancel) {
                    console.log('用户点击取消')
                    }
                }
            })  
            return;
        }
        wx.navigateTo({
            url: '../auth/auth'
        })
    },
   
    onGetOpenid: function() {
        // 调用云函数
        let that = this;
        wx.cloud.callFunction({
          name: 'login',
          data: {
    
          }
        })
        .then(res => {
          console.log('[云函数] [login]: ', res)
          let openid = res.result.openid;
          
          app.globalData.openid = openid;
          that.setData({
            openid:openid
          },async ()=>{
            const db = wx.cloud.database();
            const res = await db.collection('profiles').where({
              _openid: openid
            }).count();
            app.globalData.login =  new Boolean(res.total);
            that.setData({
              total: res.total
            })
            console.log(res);
            if(res.total == 0){
                that.addProfile();
            }
            if(res.total > 0){
                that.queryProfile();
            }
          });
          
        }).catch(err => {
          console.error('[云函数] [login] 调用失败', err)
          wx.navigateTo({
            url: '../deployFunctions/deployFunctions',
          })
        })
      },
      addProfile: function(){
        const db = wx.cloud.database();
        db.collection('profiles').add({
          // data 字段表示需新增的 JSON 数据
          data: {
            _id: this.data.openid,
            userInfo: app.globalData.userInfo,
            num: 1000,
            balance: 0,
            status: 0,
            time: new Date()
          }
        })
        .then(res => {
          console.log(res)
          console.log('[数据库] [查询记录] 成功: ', res);
          this.setData({
            num: 1000,
            balance: 0
          },()=>{
            app.globalData.num = 1000;
            app.globalData.quesTotal = 0;
            app.globalData.balance = 0;
          })
        })
        .catch((err)=>{
          console.log(err)
         
        })
      },
      queryProfile: function(){
        let that = this;
        const db = wx.cloud.database()
        db.collection('profiles')
        .doc(this.data.openid)
        .get()
        .then((res)=>{
          console.log('[数据库] [查询记录] 成功: ', res);
          let {userInfo,num,total,balance,status} = res.data;
    
          app.globalData.userInfo = userInfo;
          app.globalData.num = num;
          app.globalData.quesTotal = total;
          app.globalData.balance = balance;
          app.globalData.auth = status;
          this.setData({
              num,
              balance,
              quesTotal: total,
              auth: status,
              userInfo: Object.assign({}, this.data.userInfo, userInfo)
          })
        })
        .catch((err)=>{
          console.log(err)
          console.error('[数据库] [查询记录] 失败：', err)
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
        })
      },
    subscribeGzh: function() {
        this.setData({
            gzh_box_status: !0
        });
    },
    pgGzhCancel: function() {
        this.setData({
            gzh_box_status: !1
        });
    },
    loginCallback: function() {
        this.setData({
            userInfo: e.user,
            registerStatus: e.registerStatus
        }), this.loadBroadCast();
    },
    loadBroadCast: function() {
        var t = this, i = !1;
        e.util.request({
            url: "entry/wxapp/broad",
            showLoading: !1,
            success: function(e) {
                var n = e.data.data;
                n.length > 0 && (i = !0), t.setData({
                    showBroad: i,
                    broadList: n
                });
            },
            fail: function(t) {
                console.log("check fail");
            }
        });
    },
    beginGame: function() {
        wx.navigateTo({
            url: "../detail/detail?from=index"
        });
    },
    goQuestion: function() {
        wx.navigateTo({
            url: e.pages.question
        });
    },
    goMore: function() {
        wx.navigateTo({
            url: e.pages.more
        });
    },
    goInvite: function() {
        wx.navigateTo({
            url: e.pages.invite
        });
    },
    goJfMall: function() {
        wx.navigateTo({
            url: e.pages.jfmall
        });
    },
    loading: !1,
    showLoginModal: function() {
        this.setData({
            loginCompStatus: !0
        });
    },
    pgLoginCancel: function() {
        this.setData({
            loginCompStatus: !1
        });
    },
    pgLoginConfirm: function(t) {
        var i = t.detail.result, n = this;
        if (i.userInfo) {
            var a = i.userInfo;
            a.vid = n.data.vid, e.register(a, n.loginCallback), n.setData({
                loginCompStatus: !1
            });
        } else console.log("用户未允许授权");
    },
    animate: {
        in: "dsbk animated fadeInRight",
        out: "animated fadeOutRight"
    },
    showYLBox: function() {
        this.setData({
            ylStatus: "show",
            animate: this.animate.in
        });
    },
    hideYLBox: function() {
        this.setData({
            ylStatus: "hide",
            animate: this.animate.out
        });
    },
    showRankList: function() {
        this.setData({
            showRank: true
        },()=>{
            this.getRankList();
        });
    },
    closeRankList: function() {
        this.setData({
            showRank: !1
        });
    }
}, t(i, "loading", !1), t(i, "getRankList2", function() {
    var t = this;
    if (t.loading) console.log("慢点"); else {
        t.loading = !0;
        var i = t.data.rank;
        i.more ? e.util.request({
            url: "entry/wxapp/rank",
            data: {
                type: i.type,
                page_size: i.page_size,
                page: i.page
            },
            method: "GET",
            success: function(e) {
                0 === e.data.code && (i.page = i.page + 1, i.list = i.list.concat(e.data.data.list), 
                i.more = e.data.data.more, i.page > 3 ? i.more = !1 : i.more = 10 == e.data.data.list.length, 
                t.setData({
                    rank: i
                })), t.loading = !1;
            },
            fail: function(t) {
                console.log("load rank fail");
            }
        }) : t.loading = !1;
    }
}), t(i, "initInterstitialAd", function() {
    if (!1 !== e.canIUseInterstitialAd) {
        var t = this, i = t.data.setting;
        if (0 !== parseInt(i.screen_ad_status) && "" != i.screen_unit_id) {
            var n = null;
            wx.createInterstitialAd && ((n = wx.createInterstitialAd({
                adUnitId: i.screen_unit_id
            })).onLoad(function() {
                console.log("onLoad event emit");
            }), n.onError(function(i) {
                t.setData({
                    canIUseInterstitialAd: !1
                }), console.log("onError event emit", i);
            }), n.onClose(function(t) {
                console.log("onClose event emit", t);
            })), t.setData({
                interstitialAd: n
            }), t.showInterstitialAd();
        }
    }
}), t(i, "showInterstitialAd", function() {
    var t = this, i = this.data.interstitialAd;
    null != i && i.show().catch(function(i) {
        t.setData({
            canIUseInterstitialAd: !1
        });
    });
}), t(i, "onHide", function() {}), t(i, "onUnload", function() {}), t(i, "onShareAppMessage", function(t) {
    var i = e.getShareByScene(this.data.shareScene), n = this.data.userInfo, a = "?from=" + this.data.shareScene;
    return "1" == n.status && (a += "&vid=" + n.id), {
        title: i.title,
        path: e.pages.index + a,
        imageUrl: i.imageUrl,
        success: function(t) {},
        fail: function(t) {},
        complete: function() {}
    };
}), i));